//
//  SimActionSheet.m
//  Xubin Liu
//

#import "SimActionSheet.h"



SimImpValue(kSimActionSheetHeight, int)
SimImpValue(kSimActionTitleMargin, int)

SimImpValue(kSimActionDefaultBtnTitleColor, UIColor *);
SimImpValue(kSimActionDefaultCancelGapColor, UIColor *);
SimImpValue(kSimActionDefaultLineColorColor, UIColor *);

@implementation SimActionSheet {
    
    CGPoint panelCenter;
    float panelHeight;
    
}

-(instancetype)initWithTitle:(NSString *)caption
{
    
    if (self = [super init]) {        
        _title = caption;
        _backgroundColor = HEXRGBCOLOR(0xeeeff0);
        _showCancel = YES;
        
        _titleFontSize = 13;
        _subtitleFontSize = 11;
        _btnFontSize = 15;
        _titleColor = HEXRGBCOLOR(0x9ea0a3);
        _subtitleColor = [UIColor lightGrayColor];
        
        UIView* screenView = [[[UIApplication sharedApplication] windows] objectAtIndex:0];
        self.frame = screenView.frame;
        
        backgroundImage = [[UIView alloc] initWithFrame:screenView.bounds];
        backgroundImage.backgroundColor = [UIColor colorWithWhite:0.2 alpha:0.3];
        backgroundImage.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        
        panel = [[UIView alloc] init];
        panel.backgroundColor = [UIColor whiteColor];
        panel.translatesAutoresizingMaskIntoConstraints = NO;
        UITapGestureRecognizer *panelTap = [[UITapGestureRecognizer alloc]
                                                 initWithTarget:self
                                                 action:nil];
        [panel addGestureRecognizer:panelTap];

        
        UITapGestureRecognizer *backgroungTap = [[UITapGestureRecognizer alloc]
                         initWithTarget:self
                         action:@selector(hideAlert)];
        backgroungTap.cancelsTouchesInView = YES;
        
        [self addGestureRecognizer:backgroungTap];
        [self addSubview:backgroundImage];
        [self addSubview:panel];
    }
    
    return self;
}

-(void)showInView:(UIView *)view
{
    CGFloat btnHeight = SimValue(kSimActionSheetHeight, 50);
    CGFloat titleMargin = SimValue(kSimActionSheetHeight, 12);

    
    [view addSubview:self];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-0-[panel]-0-|"
                                                                             options:0
                                                                             metrics:nil
                                                                               views:NSDictionaryOfVariableBindings(panel)]];
    
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[panel]-0-|"
                                                                             options:0
                                                                             metrics:nil
                                                                               views:NSDictionaryOfVariableBindings(panel)]];
    

    UIView *titleLineView = nil;
    NSString *formatStr = nil;
    if (_title) {
        UILabel *mainTitle = [[UILabel alloc] init];
        mainTitle.numberOfLines = 2;
        mainTitle.translatesAutoresizingMaskIntoConstraints = NO;
        mainTitle.textAlignment = NSTextAlignmentCenter;
        mainTitle.text = _title;
        mainTitle.font = [UIFont systemFontOfSize:_titleFontSize];
        mainTitle.textColor = _titleColor;
        mainTitle.backgroundColor = [UIColor whiteColor];
        [panel addSubview:mainTitle];
        
        titleLineView = [[UIView alloc] init];
        titleLineView.backgroundColor = SimValue(kSimActionDefaultLineColorColor, HEXRGBCOLOR(0xe6e6e6));
        titleLineView.translatesAutoresizingMaskIntoConstraints = NO;
        [panel addSubview:titleLineView];
        
        [panel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-10-[mainTitle]-10-|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(mainTitle)]];
        
        [panel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-0-[titleLineView]-0-|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(titleLineView)]];

        if (_subtitle) {
            UILabel *subtitle = [[UILabel alloc] init];
            subtitle.translatesAutoresizingMaskIntoConstraints = NO;
            subtitle.font = [UIFont systemFontOfSize:_subtitleFontSize];
            subtitle.text = _subtitle;
            subtitle.numberOfLines = 2;
            subtitle.textAlignment = NSTextAlignmentCenter;
            subtitle.textColor = _subtitleColor;
            subtitle.backgroundColor = [UIColor whiteColor];
            [panel addSubview:subtitle];
            
            [panel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-10-[subtitle]-10-|"
                                                                          options:0
                                                                          metrics:nil
                                                                            views:NSDictionaryOfVariableBindings(mainTitle, subtitle, titleLineView)]];
            


            [panel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|-%f-[mainTitle]-5-[subtitle]-%f-[titleLineView(0.5)]", titleMargin, titleMargin]
                                                                          options:0
                                                                          metrics:nil
                                                                            views:NSDictionaryOfVariableBindings(mainTitle, subtitle, titleLineView)]];
        }
        else{
            [panel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|-%f-[mainTitle]-%f-[titleLineView(0.5)]", titleMargin, titleMargin]
                                                                          options:0
                                                                          metrics:nil
                                                                            views:NSDictionaryOfVariableBindings(mainTitle, titleLineView)]];
        }
        

    }
    
    __weak UIButton *preBtn = nil;
    NSInteger totalBtnCount = self.totalBtnCount();
    for (int btnIndex = 0; btnIndex < totalBtnCount; btnIndex++) {
        UIButton *button = [self btnForIndex:btnIndex];
        [panel addSubview:button];
        [panel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-0-[button]-0-|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(button)]];
        
        if (btnIndex != 0) {
            UIView *btnLineView = [[UIView alloc] init];
            btnLineView.backgroundColor = SimValue(kSimActionDefaultLineColorColor, HEXRGBCOLOR(0xe6e6e6));
            btnLineView.translatesAutoresizingMaskIntoConstraints = NO;
            [panel addSubview:btnLineView];
            
            [panel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-0-[btnLineView]-0-|"
                                                                          options:0
                                                                          metrics:nil
                                                                            views:NSDictionaryOfVariableBindings(btnLineView)]];

            [panel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:[preBtn]-0-[btnLineView(0.5)]-0-[button(%f)]", btnHeight]
                                                                          options:0
                                                                          metrics:nil
                                                                            views:NSDictionaryOfVariableBindings(preBtn, btnLineView, button)]];
        }
        else{
            if (titleLineView) {
                formatStr = [NSString stringWithFormat:@"V:[titleLineView]-0-[button(%f)]", btnHeight];
                [panel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:formatStr
                                                                              options:0
                                                                              metrics:nil
                                                                                views:NSDictionaryOfVariableBindings( titleLineView, button)]];
            }
            else{
                formatStr = [NSString stringWithFormat:@"V:|-0-[button(%f)]", btnHeight];
                [panel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:formatStr
                                                                              options:0
                                                                              metrics:nil
                                                                                views:NSDictionaryOfVariableBindings( button)]];
            }
        }
        
        preBtn = button;
    }
    
    
    if (_showCancel) {
        UIColor *cancelGapColor = SimValue(kSimActionDefaultCancelGapColor, HEXRGBCOLOR(0xeeeff0));
        UIView *gapView = [[UIView alloc] init];
        gapView.backgroundColor = cancelGapColor;
        gapView.translatesAutoresizingMaskIntoConstraints = NO;
        [panel addSubview:gapView];
        
        UIButton *cancelBtn = [self btnForIndex:totalBtnCount];
        [panel addSubview:cancelBtn];
        
        
        [panel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-0-[gapView]-0-|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(gapView)]];
        
        [panel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-0-[cancelBtn]-0-|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(cancelBtn)]];

        
        [panel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:[preBtn]-0-[gapView(5)]-0-[cancelBtn(%f)]-0-|", btnHeight]
                                                                      options:0
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(preBtn, gapView, cancelBtn)]];
    }
    else{
        [panel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[preBtn]-0-|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(preBtn)]];
    }
    [self layoutSubviews];
    
    backgroundImage.alpha = 0;
    panelCenter = panel.center;
    panelHeight = panel.frame.size.height / 2;
    
    panel.center = CGPointMake(panelCenter.x, panelCenter.y + panelHeight*2);
    
    [UIView animateWithDuration:0.2
                          delay:0
                        options:7<<16
                     animations:^{
                         backgroundImage.alpha = 1;
                         panel.center = panelCenter;
                     } completion:nil];
}

- (UIButton *)btnForIndex:(NSInteger)index
{
    UIColor *titleColor = SimValue(kSimActionDefaultBtnTitleColor, kSimActionSheetDefaultBtnColor);
    NSString *titleStr = index < _totalBtnCount() ? _btnTitleForIndex(index) : @"取消";
    
    UIButton *button = [[UIButton alloc] init];
    button.tag = index;
    button.translatesAutoresizingMaskIntoConstraints = NO;
    [button setTitle:titleStr forState:UIControlStateNormal];
    [button setTitleColor:_btnTextColorForIndex? _btnTextColorForIndex(index) : titleColor forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:_btnFontSize];
    [button addTarget:self action:@selector(actionButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}


- (void)actionButtonPressed:(UIButton *)button
{
    NSInteger index = button.tag;
    if (index < _totalBtnCount()) {
        if(self.clickOnIndex){
            self.clickOnIndex(index);
        }
    }
    
    [self hideAlert];
}

- (void) hideAlert
{
    [UIView animateWithDuration:0.2
                          delay:0
                        options:7<<16
                     animations:^{
                         backgroundImage.alpha = 0;
                         panel.frame = CGRectMake(0, panel.frame.origin.y + panel.frame.size.height, panel.frame.size.width, panel.frame.size.height);
                     } completion:^(BOOL finished) {
                         [self removeFromSuperview];
                     }];
}

@end
